#!/bin/bash

show_help() {
    echo -e "Options:"
    echo -e "\t--skip-libvirt           skip install libvirt checker"
    echo -e "\t-v | --verbose           show more messages"
    echo -e "\t-h | --help              show this help"
    exit
}

DEBUG=false
skip_libvirt=false

cmdopts=$(getopt --longoptions skip-libvirt,verbose,help \
                     --options +hv -- "$@")

while true; do
  case "$1" in
    -h | --help )
        show_help
        exit ;;
    --skip-libvirt )
        skip_libvirt=true
        shift;;
    -v | --verbose )
        DEBUG=true
        shift;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

if $DEBUG; then
    set -x
fi

# part 1: local install
installto="/usr/local"
sudo cp do_fip \
        do_libvirt \
        do_osc \
        do_carrier \
        do_sysctl \
        do_gnocchi \
        nyyos ${installto}/bin/
sudo cp doc/nyyosrc.5 ${installto}/share/man/man5/
sudo chmod 755 ${installto}/bin/nyyos
sudo chmod 644 ${installto}/bin/do_fip
sudo chmod 644 ${installto}/bin/do_gnocchi \
 ${installto}/bin/do_osc \
 ${installto}/bin/do_carrier \
 ${installto}/bin/do_sysctl \
 ${installto}/bin/do_libvirt \
 ${installto}/share/man/man5/nyyosrc.5

. ~/.nyyosrc || { set +x; echo -e "~/.nyyosrc not found. See the nyyosrc(5) man page for more information."; exit -1; }

chmod 600 ~/.nyyosrc

# part 2: openstack
tar --exclude-vcs -zcf /tmp/nyyos.tgz \
../nyyos/remote/detectip.sh \
../nyyos/remote/fastosc.sh \
../nyyos/remote/baseosc.sh \
../nyyos/remote/check-servers-fip.sh \
../nyyos/remote/test-gnocchi.sh

sudo scp /tmp/nyyos.tgz root@$controller:/tmp/
dests=(kolla_toolbox gnocchi_api)
for x in ${dests[@]}; do
    sudo ssh root@$controller docker cp /tmp/nyyos.tgz $x:/
    sudo ssh root@$controller docker exec -uroot $x tar zxvf /nyyos.tgz
    sudo ssh root@$controller docker exec -uroot $x chmod -R 755 /nyyos
done

# part 3: libvirt checker
if ! $skip_libvirt; then
    sudo scp check_libvirt.sh vmchecker prickvm root@$controller:/usr/local/bin/
    sudo ssh -t root@$controller /bin/bash /usr/local/bin/check_libvirt.sh install
fi

# part 4: carrier|sysctl checker
    sudo scp carrier_check sysctl_check root@$controller:/usr/local/bin/
